package cn.yll.web;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.Arrays;

/**
 * 商城后端服务
 * @author yangll
 */
@Slf4j
@EnableDiscoveryClient
@EnableFeignClients({"cn.yll.api"})
@SpringBootApplication(scanBasePackages = {"cn.yll.common","cn.yll.api","cn.yll.web"})
public class WebServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebServiceApplication.class, args);
        log.info("===============================================");
        log.info("==============商城web项目启动成功=================");
        log.info("===============================================");
        initSentinelRule();
    }

    private static void initSentinelRule() {
        String resourceName = "resourceNameXXX";
        //资源resourceNameXXX 每秒2次请求调用，超过直接报错返回
        FlowRule flowRule = new FlowRule(resourceName).setGrade(RuleConstant.FLOW_GRADE_QPS).setCount(2).setStrategy(RuleConstant.STRATEGY_DIRECT);
        FlowRuleManager.loadRules(Arrays.asList(flowRule));
        //资源resourceNameXXX 请求数3秒超4次的时候，异常请求数超5次，服务熔断2秒
        DegradeRule degradeRule1 = new DegradeRule(resourceName).setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT).setCount(5).setTimeWindow(2).setStatIntervalMs(3000).setMinRequestAmount(4);
        //资源resourceNameXXX 请求数3秒超4次的时候，超过500ms响应的慢请求超过50%，服务熔断2秒
        DegradeRule degradeRule2 = new DegradeRule(resourceName).setGrade(RuleConstant.DEGRADE_GRADE_RT).setCount(500).setTimeWindow(2).setStatIntervalMs(3000).setMinRequestAmount(4).setSlowRatioThreshold(0.5);
        DegradeRule degradeRule3 = new DegradeRule(resourceName).setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO).setCount(0.5).setTimeWindow(2).setStatIntervalMs(3000).setMinRequestAmount(4).setSlowRatioThreshold(0.5);
        DegradeRuleManager.loadRules(Arrays.asList(degradeRule1, degradeRule2, degradeRule3));
    }
}
